package cn.fl.flow.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.flow.service.IFlowFrmAthRecService;
import cn.fl.flow.vo.FlowFrmAthRecVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysDictionaryService;
import fl.constant.facade.framework.constant.DictionaryConstant;

/**
 * @Description: 流程中节点附加页面会有权限控制, 节点上审核人员会配置这个功能权限。 控制层
 */
@Controller
@RequestMapping("/flow/flowfrmathrec")
public class FlowFrmAthRecController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(FlowFrmAthRecController.class);

	/**
	 * FlowFrmAthRec 服务层BEAN
	 */
	@Autowired
	private IFlowFrmAthRecService flowFrmAthRecService;
	
	/**
	 * 数据字典服务
	 */
	@Autowired
	private ISysDictionaryService sysDictionaryService;

	/**
	 * 到流程设置新增页面
	 */
	@RequestMapping(value = "/toFlowFormAuthConfig.do", method = { RequestMethod.GET})
	public ModelAndView toFlowFormAuthConfig(HttpServletRequest request, HttpServletResponse response) {
		String procDefKey = request.getParameter("procDefKey");
		String procDefId = request.getParameter("procDefId");
		String procInstId = request.getParameter("procInstId");
		String taskId = request.getParameter("taskId");
		String taskDefKey = request.getParameter("taskDefKey");
		String preTaskId = request.getParameter("preTaskId");
		String dataId = request.getParameter("dataId");
		String branchKey = request.getParameter("branchKey");
		
		ModelAndView view = new ModelAndView("flow/formauth/flowFormAuthConfig");
		view.addObject("procDefKey", procDefKey);
		view.addObject("procDefId", procDefId);
		view.addObject("procInstId", procInstId);
		view.addObject("taskId", taskId);
		view.addObject("taskDefKey", taskDefKey);
		if(StringUtils.isEmpty(preTaskId)){
			preTaskId = "";
		}
		view.addObject("preTaskId", preTaskId);
		view.addObject("dataId", dataId);
		view.addObject("branchKey", branchKey);
		//获取需要配置的选项
		try {
			String sysCd = CurrentThreadContext.getFlServiceSysCd();
			String orgCd = CurrentThreadContext.getCurrentOrgCd();
			String key = PropertiesCacheUtils.getProperty(DictionaryConstant.CODE_FLW_FRM_ATH_CD);
			List<String> codeGrpCdList = new ArrayList<>();
			codeGrpCdList.add(key);
			Map<String, List<KeyValueVO>> dicMap = this.sysDictionaryService.getMultiKvList(sysCd, orgCd, codeGrpCdList);
			view.addObject("flowFormAuthConfigList", dicMap.get(key));
		} catch (Exception e) {
			BaseLogUtils.error(logger, "toFlowFormAuthConfig", "获取数据字典信息失败!" , e);
		}
		return view;
	}

	/**
	 * 新增选项
	 * 逻辑：
	 * 1、因为页面权限默认是都可以使用的, 所以为了不影响使用把前端未勾选的作为禁用选项存入DB, 当页面获取权限的时候是找到配置项为禁用,找不到为启用。
	 * 2、当用户选择了"全部修改"选项后, 不需要保存任何值直接返回前端提示成功。
	 * 3、当勾选了非"全部修改"选项后要把"全部修改"过滤掉不保存DB
	 */
	@RequestMapping(value = "/addAndModify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		
		String procDefKey = request.getParameter("procDefKey");
		String procDefId = request.getParameter("procDefId");
		String procInstId = request.getParameter("procInstId");
		String taskId = request.getParameter("taskId");
		String taskDefKey = request.getParameter("taskDefKey");
		String preTaskId = request.getParameter("preTaskId");
		String dataId = request.getParameter("dataId");
		String branchKey = request.getParameter("branchKey");
		String authFormItem = request.getParameter("authFormItem");//未勾选的项
		String authFormCheckedItem = request.getParameter("authFormCheckedItem");//已勾选的项
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
		
		if(StringUtils.isEmpty(dataId)){
			result.setInfo("业务主键不能为空!");
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			return result;
		}
		
		try {
			String AE = PropertiesCacheUtils.getProperty(DictionaryConstant.CODE_FLW_FRM_ATH_AE_CD);
			com.alibaba.fastjson.JSONArray itemCheckedArray = com.alibaba.fastjson.JSONArray.parseArray(authFormCheckedItem);
			List<FlowFrmAthRecVO> list = new ArrayList<>();
			boolean hasAE = false;
			if(null != itemCheckedArray){//因为前端选择的项是不保存到数据库的,所以
				JSONObject itemObj = null;
				for (Object object : itemCheckedArray) {
					itemObj = (JSONObject)object;
					String athCd = itemObj.getString("athCd");
					if(athCd.equals(AE)){
						hasAE = true;
						break;
					}
				}
				
				if(hasAE){//如果是全部修改则把之前新增数据删除掉
					this.flowFrmAthRecService.addAndModify(list, Long.valueOf(dataId), taskId);
					return result;//如果有"全部修改"按钮则不保存任何数据
				}
				
			}
			
			com.alibaba.fastjson.JSONArray itemArray = com.alibaba.fastjson.JSONArray.parseArray(authFormItem);
			
			FlowFrmAthRecVO entity = null;
			if(null != itemArray){
				JSONObject itemObj = null;
				Date date = new Date();
				String sysCd = CurrentThreadContext.getFlServiceSysCd();
				Long usrId = CurrentThreadContext.getCurrentUserId();
				for (Object object : itemArray) {
					itemObj = (JSONObject)object;
					String athCd = itemObj.getString("athCd");
					String athCdNm = itemObj.getString("athCdNm");
					
					if(athCd.equals(AE))continue;//不保存"全部修改"选项
					
					entity = new FlowFrmAthRecVO();
					entity.setAthCd(athCd);
					entity.setTaskDefKey(taskDefKey);
					entity.setTaskId(taskId);
					entity.setCrtTm(date);
					entity.setAthCdNm(athCdNm);
					entity.setBranchKey(branchKey);
					entity.setDataId(Long.valueOf(dataId));
					entity.setCrtUsrId(usrId);
					entity.setIsDel(BaseConstant.IS_YESNO_NO);
					entity.setProcDefId(procDefId);
					entity.setProcInstId(procInstId);
					entity.setProcDefKey(procDefKey);
					entity.setPTaskId(preTaskId);
					entity.setSysCd(sysCd);
					entity.setMdfTm(date);
					entity.setMdfUsrId(usrId);
					list.add(entity);
				}
				
			}
			//如果集合是空的也要请求次服务,因为可能之前有保存过记录所以要清除掉之前的数据,即使没有新数据要保存也要这样处理
			boolean pass = this.flowFrmAthRecService.addAndModify(list, Long.valueOf(dataId), taskId);
			if(!pass){
				result.setInfo("新增失败!");
				result.setSuccess(BaseConstant.IS_YESNO_NO);
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.", CurrentThreadContext.getCurrentUserName(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败！", CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;
	}
}

